<template>
  <ContentWrap>
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.totalPunches || 0 }}</div>
            <div class="stats-label">总打卡数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.todayPunches || 0 }}</div>
            <div class="stats-label">今日打卡</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.weekPunches || 0 }}</div>
            <div class="stats-label">本周打卡</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-number">{{ stats.monthPunches || 0 }}</div>
            <div class="stats-label">本月打卡</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="mb-4"
    >
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="选择开始日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          placeholder="选择结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 打卡记录表格 -->
    <el-table
      v-loading="loading"
      :data="list"
      stripe
      style="width: 100%"
    >
      <el-table-column label="ID" prop="id" width="80" />
      <el-table-column label="用户ID" prop="userId" width="100" />
      <el-table-column label="打卡日期" prop="punchDate" width="120">
          <template #default="{ row }">
            {{ formatDate(row.punchDate) }}
          </template>
        </el-table-column>
        <el-table-column label="阅读本数" prop="bookCount" width="100">
          <template #default="{ row }">
            {{ row.bookCount || 0 }} 本
          </template>
        </el-table-column>
        <el-table-column label="阅读书籍" prop="bookIds" width="120">
          <template #default="{ row }">
            {{ row.bookIds || '[]' }}
          </template>
        </el-table-column>
        <el-table-column label="累计天数" prop="totalDays" width="100">
          <template #default="{ row }">
            {{ row.totalDays || 0 }} 天
          </template>
        </el-table-column>
        <el-table-column label="是否公开" prop="isPublic" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isPublic ? 'success' : 'info'">
              {{ row.isPublic ? '公开' : '私密' }}
            </el-tag>
          </template>
        </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="handleDetail(row)"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-model:current="queryParams.current"
      v-model:size="queryParams.size"
      :total="total"
      @pagination="getList"
    />

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="打卡详情"
      width="600px"
      append-to-body
    >
      <el-descriptions v-if="detailData" :column="2" border>
        <el-descriptions-item label="用户ID">{{ detailData.userId }}</el-descriptions-item>
        <el-descriptions-item label="打卡日期">{{ formatDate(detailData.punchDate) }}</el-descriptions-item>
        <el-descriptions-item label="阅读本数">{{ detailData.bookCount || 0 }} 本</el-descriptions-item>
        <el-descriptions-item label="累计天数">{{ detailData.totalDays || 0 }} 天</el-descriptions-item>
        <el-descriptions-item label="是否公开">{{ detailData.isPublic ? '公开' : '私密' }}</el-descriptions-item>
        <el-descriptions-item label="打卡时间">{{ formatDateTime(detailData.punchTime) }}</el-descriptions-item>
        <el-descriptions-item label="阅读书籍" :span="2">{{ detailData.bookIds || '[]' }}</el-descriptions-item>
        <el-descriptions-item label="阅读心得" :span="2">
          <div class="whitespace-pre-wrap">{{ detailData.commentText || '无' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">{{ formatDateTime(detailData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间" :span="2">{{ formatDateTime(detailData.updateTime) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/formatTime'
import {
  getStudyPunchPage,
  getStudyPunchStats,
  deleteStudyPunch,
  type StudyPunchVO,
  type StudyPunchStatsVO
} from '@/api/miniprogram/checkin'

defineOptions({ name: 'MiniProgramCheckin' })

// 响应式数据
const loading = ref(false)
const list = ref<StudyPunchVO[]>([])
const total = ref(0)
const detailVisible = ref(false)
const detailData = ref<StudyPunchVO | null>(null)
const stats = ref<StudyPunchStatsVO>({
  totalPunches: 0,
  todayPunches: 0,
  weekPunches: 0,
  monthPunches: 0
})

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  userId: undefined,
  startDate: undefined,
  endDate: undefined
})

// 获取打卡记录列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getStudyPunchPage(queryParams)
    // 适配后端返回的数据结构
    if (res.data && res.data.records) {
      list.value = res.data.records || []
      total.value = res.data.total || 0
    } else if (res.data && Array.isArray(res.data)) {
      // 如果直接返回数组
      list.value = res.data
      total.value = res.data.length
    } else {
      list.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取打卡记录失败:', error)
    ElMessage.error('获取打卡记录失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStats = async () => {
  try {
    const res = await getStudyPunchStats()
    if (res.code === 200) {
      stats.value = res.data || {
        todayPunches: 0,
        weekPunches: 0,
        monthPunches: 0,
        totalPunches: 0
      }
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 搜索
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置
const resetQuery = () => {
  queryParams.current = 1
  queryParams.size = 10
  queryParams.userId = undefined
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  getList()
}

// 查看详情
const handleDetail = (row: StudyPunchVO) => {
  detailData.value = row
  detailVisible.value = true
}

// 删除打卡记录
const handleDelete = async (row: StudyPunchVO) => {
  try {
    await ElMessageBox.confirm('确定要删除这条打卡记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteStudyPunch(row.id!)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await getList()
      await getStats()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  getList()
  getStats()
})
</script>

<style scoped>
.stats-card {
  text-align: center;
}

.stats-content {
  padding: 20px;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}
</style>